﻿
using Extention.ENode.Rpc.Runtime.Communally.Entitys.Address;
using Extention.ENode.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Extention.ENode.Rpc.Routing.Impl
{
    public class RedisHealthyCheckRouterManager
    {

        private readonly ICacheProvider _cacheProvider;
        public RedisHealthyCheckRouterManager(ICacheProvider cacheProvider)
        {
            _cacheProvider = cacheProvider;
        }

        public readonly string Key = "ESTARTCACHE:ROUTER:RPCROUTERKEY-SERVERNAME";
        public readonly string ZBalanceKey = "ESTARTCACHE:ROUTER:RPCROUTERKEY-KEY";
        private readonly int DB = 11;

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <param name="serverName"></param>
        /// <returns></returns>
        public async Task<IEnumerable<IpAddressModel>> GetBalanceAsync(string serverName)
        {
            var HasKey = await _cacheProvider.HashExistsAsync(ZBalanceKey, serverName, DB, false);
            if (HasKey)
            {
                var serverList = _cacheProvider.HashGet<List<IpAddressModel>>(ZBalanceKey, serverName, DB, false);
                if (serverList == null || serverList.Count == 0)
                {

                    throw new Exception($"未找到有效的服务节点!");
                }
                return serverList;
            }
            else
            {
                throw new Exception($"未找到有效的服务节点!");
            }

        }


        public async Task<bool> RemoveBanlanceasync(IpAddressModel addressModel)
        {


            var HasKey = await _cacheProvider.HashExistsAsync(ZBalanceKey, addressModel.ServiceName, DB, false);
            if (HasKey)
            {
                var serverList = _cacheProvider.HashGet<List<IpAddressModel>>(ZBalanceKey, addressModel.ServiceName, DB, false);
                if (serverList == null)
                {
                    serverList = new List<IpAddressModel>();
                }
                serverList = serverList.Where(n => !(n.Ip == addressModel.Ip && n.Port == addressModel.Port)).ToList();
                if (serverList != null)
                {
                    await _cacheProvider.HashSetAsync(ZBalanceKey, addressModel.ServiceName, serverList, DB, false);
                }
                else
                {
                    await _cacheProvider.HashDeleteAsync(ZBalanceKey, addressModel.ServiceName, DB, false);
                }
            }
            return true;
        }

        /// <summary>
        /// 获取所有服务的key
        /// </summary>
        /// <returns></returns>
        public async Task<List<string>> GetServerKey()
        {

            var serverList = await _cacheProvider.HashKeysStringAsync<string>(ZBalanceKey, DB, false);
            if (serverList == null || serverList.Count == 0)
            {

                throw new Exception($"未找到有效的服务节点!");
            }
            return serverList;
        }

        public async Task<bool> CheckAsync()
        {

            var server = await GetServerKey();

            foreach (var item in server)
            {
                var balance = await GetBalanceAsync(item);
                foreach (var blan in balance)
                {
                    Console.WriteLine($"开始检查！{blan.ServiceName}");
                    var healthyUrl = blan.CreateHealthyCheckUrl();
                    try
                    {
                        var result = HttpHelper.HttpGet(healthyUrl, "", 3000);
                        Console.WriteLine($"服务：{blan.ServiceName}，检查地址：{healthyUrl},结果：{result}");
                    }
                    catch (Exception ex)
                    {
                        var b = await RemoveBanlanceasync(blan);
                        Console.WriteLine($"服务：{blan.ServiceName}，检查地址：{healthyUrl},结果：{ex.Message}");
                    }
                }
            }
            return true;
        }
    }
}
